<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="/mi_project/js/jquery.js"></script>
    <script src="/mi_project/js/jquery.cookie.js"></script>
    <script src="/mi_project/js/common.js"></script>
    <link rel="stylesheet" href="/mi_project/css/base.css">
    <link rel="stylesheet" href="/mi_project/css/index-top.css">
    <link rel="stylesheet" href="/mi_project/css/cart.css">
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_2917027_4icbe1xja37.css">
    <script src="/mi_project/layui/layui.js"></script>
    <link rel="stylesheet" href="/mi_project/layui/css/layui.css">
</head>

<body>
    <div class="header-1">
    </div>
    <div class="header-cart-2">
        <div class="w">
            <div class="loge"><a href=""></a></div>
            <div class="header-nav">
                <h2>我的购物车</h2>
            </div>
        </div>
    </div>
    <div class="cartBody">
        <div class="shoppingBar">
            <h2>购物清单</h2>
            <table>
                <tbody>
                    <tr>
                        <th><input type="checkbox" title="全选"></th>
                        <th>商品名称</th>
                        <th>数量</th>
                        <th>单价（元）</th>
                        <th>金额（元）</th>
                        <th>操作</th>
                    </tr>

                    <!-- <tr class="commodity">
                        <th><input type="checkbox" class="input" value="3"></th>
                        <th class="content"><img src="image/banzhur.png" width="100px" height="100px">
                            <p>乐捐 </p>
                        </th>
                        <th><button type="button" class="lessGoods">
                                -
                            </button> <input type="text" class="amount" value="1"><button type="button">
                                +
                            </button></th>
                        <th>10</th>
                        <th class="money">
                            10
                        </th>
                        <th><a href="javascript:;" class="glyphicon glyphicon-remove">删除
                            </a></th>
                    </tr> -->
                </tbody>
            </table>
            <div class="shoppingBar-footer">
                <div class="manage"><span class="delAll">
                        删除所选商品
                    </span> <span class="return">
                        继续购物
                    </span></div> <button id="go" type="button">
                    去结算
                </button>
                <div class="buy"><span>
                        0
                    </span>
                    件商品总计:
                    <span>
                        ￥0
                    </span>
                </div>
            </div>
        </div>

    </div>
</body>

</html>
<script>
    let cartData = {}
    if ($.cookie('user')) {
        //数据整理
        $.ajax({
            url: urls + '/cart/lists',
            data: {
                userId: $.cookie('user').id
            },
            success: function (backData) {
                for (let key in backData.data) {
                    cartData[key] = {};
                    cartData[key]['goodsId'] = backData.data[key].goodsId;
                    cartData[key]['goodsCount'] = backData.data[key].goodsCount;
                    cartData[key]['goodsThumb'] = backData.data[key].goods.goodsThumb;
                    cartData[key]['goodsName'] = backData.data[key].goods.goodsName;
                    cartData[key]['id'] = backData.data[key].id;
                    cartData[key]['shopPrice'] = backData.data[key].goods.shopPrice;
                }
                // let letCart = { "carts": [], "userId": $.cookie('user').id };
                // letCart.carts[cartData[key]['id']] = { "goodsId": cartData[key]['goodsId'], "goodsCount": cartData[key]['goodsCount'] };
                cartOut()
            }
        })
    } else {
        let cartDataT = JSON.parse(localStorage.getItem('userData'));
        console.log(cartDataT.length);
        let i = 0;
        let goodsIdS = { goodsIds: [] };
        for (let key in cartDataT) {
            goodsIdS['goodsIds'].push(key);
        };
        $.ajax({
            url: urls + '/goods/getGoodsByIds',
            data: {
                goodsIds: goodsIdS.goodsIds
            },
            success: function (backData) {
                for (let key in cartDataT) {
                    cartData[i] = {};
                    cartData[i]['goodsId'] = key;
                    cartData[i]['goodsCount'] = cartDataT[key];
                    cartData[i]['goodsThumb'] = backData.data[i].goodsThumb;
                    cartData[i]['goodsName'] = backData.data[i].goodsName;
                    cartData[i]['id'] = null;
                    cartData[i]['shopPrice'] = backData.data[i].shopPrice;
                    i++;
                }
                cartOut()
            }
        })
    }
    function cartOut() {
        let letCart = {};
        let cartDataT = null;
        if ($.cookie('user')) {
            letCart = { "carts": [], "userId": $.cookie('user').id };
        } else {
            letCart = {
                "carts": []
            }
            cartDataT = JSON.parse(localStorage.getItem('userData'));
        }
        for (let key in cartData) {
            letCart.carts[cartData[key]['id']] = { "goodsId": cartData[key]['goodsId'], "goodsCount": cartData[key]['goodsCount'] };
            $('.shoppingBar tbody').append(`<tr class="commodity">
                        <th><input type="checkbox" class="input" value="1"></th>
                        <th class="content"><img src="${cartData[key]['goodsThumb']}" width="100px" height="100px">
                            <p>${cartData[key]['goodsName']}</p>
                        </th>
                        <th><button type="button" class="lessGoods">
                                -
                            </button> <input type="text" class="amount" cartId="${cartData[key]['id']}" goodsId="${cartData[key]['goodsId']}" value="${cartData[key]['goodsCount']}"> <button type="button">
                                +
                            </button></th>
                        <th>${cartData[key]['shopPrice']}</th>
                        <th class="money">${cartData[key]['shopPrice'] * cartData[key]['goodsCount']}</th>
                        <th><a href="javascript:;" class="glyphicon glyphicon-remove">删除
                            </a></th>
                    </tr>`)
        }
        count()
        $('.shoppingBar').on('click', 'input:eq(0)', function () {
            $('.shoppingBar input').prop('checked', $(this).prop('checked'));
            count();
        })
        $('.shoppingBar').on('click', ' input:gt(0)', function () {
            count();
            let flag = true;
            for (let j = 1; j < $('.shoppingBar input').length; j++) {
                if ($('.shoppingBar input')[j].checked == false) { flag = false; }
            }
            if (flag) {
                $('.shoppingBar input')[0].checked = true;
            } else {
                $('.shoppingBar input')[0].checked = false;
            }
        })
        $('.glyphicon-remove').on('click', function () {
            if ($.cookie('user')) {
                $.ajax({
                    url: urls + '/cart/remove',
                    data: {
                        cartId: $(this).parent().parent().find('.amount').attr('cartId'),
                        userId: letCart.userId,
                    },
                })
            } else {
                delete cartDataT[$(this).parent().parent().find('.amount').attr('goodsId')];
                localStorage.setItem('userData', JSON.stringify(cartDataT));
            }
            $(this).parent().parent().detach();
            count();
        })
        $('.delAll').on('click', function () {
            $('.commodity').each(function (index, item) {
                if ($(item).find('input[type="checkbox"]').prop('checked') == true) {
                    if ($.cookie('user')) {
                        $.ajax({
                            url: urls + '/cart/remove',
                            data: {
                                cartId: $(this).find('.amount').attr('cartId'),
                                userId: letCart.userId,
                            },
                        })
                    } else {
                        delete cartDataT[$(this).find('.amount').attr('goodsId')];
                        localStorage.setItem('userData', JSON.stringify(cartDataT));
                    }
                    $(this).detach();
                }
            })
            count();
        })
        $('.shoppingBar tbody').on('click', '.amount+button', function () {
            $(this).prev().val($(this).prev().val() * 1 + 1);
            $(this).parent().next().next().text($(this).parent().next().text() * $(this).prev().val());
            if ($.cookie('user')) {
                $.ajax({
                    url: urls + '/cart/change',
                    data: {
                        cartId: $(this).prev().attr('cartId'),
                        userId: letCart.userId,
                        goodsId: letCart.carts[$(this).prev().attr('cartId')].goodsId,
                        goodsCount: $(this).prev().val()
                    },
                })
            } else {
                cartDataT[$(this).prev().attr('goodsId')] = $(this).prev().val();
                localStorage.setItem('userData', JSON.stringify(cartDataT));
            }
            count();
        })
        $('.shoppingBar tbody').on('click', '.lessGoods', function () {
            if ($(this).next().val() * 1 <= 1) {
                alert("不可以哦")
            } else {
                $(this).next().val($(this).next().val() * 1 - 1);
                $(this).parent().next().next().text($(this).parent().next().text() * $(this).next().val());
                // $.ajax({
                //     url: urls + '/cart/change',
                //     data: {
                //         cartId: $(this).next().attr('cartId'),
                //         userId: letCart.userId,
                //         goodsId: letCart.carts[$(this).next().attr('cartId')].goodsId,
                //         goodsCount: $(this).next().val()
                //     },
                // })
                if ($.cookie('user')) {
                    $.ajax({
                        url: urls + '/cart/change',
                        data: {
                            cartId: $(this).next().attr('cartId'),
                            userId: letCart.userId,
                            goodsId: letCart.carts[$(this).next().attr('cartId')].goodsId,
                            goodsCount: $(this).next().val()
                        },
                    })
                } else {
                    cartDataT[$(this).next().attr('goodsId')] = $(this).next().val();
                    localStorage.setItem('userData', JSON.stringify(cartDataT));
                }
                count();
            }
        })
        $('.amount').on('input propertychange', function () {
            if ($(this).val() * 1 < 1) {
                alert("不可以哦");
                $(this).val(1);
            } else {
                $(this).parent().next().next().text($(this).parent().next().text() * $(this).val())
                $.ajax({
                    url: urls + '/cart/change',
                    data: {
                        cartId: $(this).attr('cartId'),
                        userId: letCart.userId,
                        goodsId: letCart.carts[$(this).attr('cartId')].goodsId,
                        goodsCount: $(this).val()
                    },
                })
            }
            count()
        })

        function count() {
            let amounts = 0;
            let amountMoney = 0;
            $('.money').each(function (index, item) {
                if ($(item).parent().find('input[type="checkbox"]').prop('checked') == true) {
                    amountMoney += item.innerText * 1;
                }
            })
            $('.amount').each(function (index, item) {
                if ($(item).parent().parent().find('input[type="checkbox"]').prop('checked') == true) {
                    amounts += item.value * 1;
                }
            })
            $('.buy span:eq(0)').text(amounts);
            $('.buy span:eq(1)').text(amountMoney + '￥');
        }
        $('#go').click(function () {
        if ($.cookie('user')) {
            if ($('.commodity').length != 0) {

                let a = [];
                $('.commodity').each(function (index, item) {
                    if ($(item).find('input[type="checkbox"]').prop('checked') == true) {
                        a.push($(item).find('.amount').attr('cartId'));
                    }
                })
                localStorage.setItem('checkboxId', JSON.stringify(a));
                layer.open({
                    skin: 'demo-class',
                    type: 2,
                    content: 'orderNow.html',
                    end: function () {
                        let ok = JSON.parse(localStorage.getItem('ok'));
                        if (ok == 'ok') {
                            $('.commodity').each(function (index, item) {
                                if ($(item).find('input[type="checkbox"]').prop('checked') == true) {
                                    $.ajax({
                                        url: urls + '/cart/remove',
                                        data: {
                                            cartId: $(this).find('.amount').attr('cartId'),
                                            userId: $.cookie('user').id,
                                        },
                                    })
                                    $(this).detach();
                                }
                            })
                            localStorage.removeItem('ok');
                            count();
                        }
                        localStorage.removeItem('checkboxId');
                        count();
                    }
                });
            } else {
                layer.msg('请先添加商品')
            }
        } else {
            layer.msg('请先登录');
            location.href='login.html'+'?callback='+encodeURIComponent(location.href);
        }
    })
    }
    
</script>